package com.lemon.funplus;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.lemon.funplus.fragment.YoutubeFragment;
import com.lemon.funplus.object.HomeObject;
import com.lemon.funplus.video.FullScreenVideoStreamView;
import com.lemon.funplus.video.VideoControllerStreamView;

@SuppressLint({ "DefaultLocale", "NewApi" })
public class VideoPlayActivity extends FragmentActivity implements FullScreenVideoStreamView.ToggleFullScreen {
	// private final String VIDEO_STREAM =
	// "http://www.pocketjourney.com/downloads/pj/video/famous.3gp";
	private FullScreenVideoStreamView mVideoView;
	private ProgressBar bar;
	int height;
	int width;
	RelativeLayout relativeLayout;
	HomeObject homeObject;
	ViewPager viewPager;
	int index = -1;
	private WebView webViewFB = null;
	private WebView childWebView = null;
	private LinearLayout parentLayout;
	YoutubeFragment menuFragment;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		if (Build.VERSION.SDK_INT < 16) {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		} else {
			View decorView = getWindow().getDecorView();
			int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
			decorView.setSystemUiVisibility(uiOptions);
		}
		setContentView(R.layout.video_stream);

		Bundle extras = getIntent().getExtras();
		if (getIntent().hasExtra("object_video"))
			homeObject = (HomeObject) extras.getSerializable("object_video");
		if (homeObject != null) {
			homeObject.showinfo();
		}
		findviewbyid();
		playVideo();
		mVideoView.mMediaController.setTitle(homeObject.gettitle());

		webViewFB = new WebView(this);
		webViewFB.setWebViewClient(new FaceBookClient());
		webViewFB.setWebChromeClient(new FBChromeClient());
		parentLayout = (LinearLayout) findViewById(R.id.parentLayout);

		webViewFB.setLayoutParams(getLayoutParams());

		final WebSettings webSettings = webViewFB.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setSupportMultipleWindows(true);
		parentLayout.addView(webViewFB);
		webViewFB.loadDataWithBaseURL("http://funplus.vn/", getHTMLData(homeObject.getfb_link()), "text/html", null, "");

	}

	void findviewbyid() {
		relativeLayout = (RelativeLayout) findViewById(R.id.video_realati_videoview);
		bar = (ProgressBar) findViewById(R.id.videoplayerPreloader);
		mVideoView = (FullScreenVideoStreamView) findViewById(R.id.video_view);
	}

	private void playVideo() {
		int indexId = homeObject.getcontent().indexOf("watch?v=") + "watch?v=".length();
		String url = homeObject.getcontent().substring(indexId, indexId + 11);

		// mVideoView.setVisibility(View.GONE);
		// bar.setVisibility(View.GONE);
		// mVideoView.setDimensions(0, 0);
		// menuFragment = YoutubeFragment.newInstance(url);
		// FragmentTransaction fragmentTransaction =
		// getSupportFragmentManager().beginTransaction();
		// fragmentTransaction.replace(R.id.video_container, menuFragment,
		// menuFragment.getClass().getName());
		// fragmentTransaction.commit();

		Log.e("", "url: " + url);
		mVideoView.setOnToggleFullScreen(this);
		mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {
				bar.setVisibility(View.GONE);
			}
		});

		calculateVideoViewSize();
		mVideoView.setMediaController(new VideoControllerStreamView(this));
		mVideoView.setDimensions(width, height);
		String lYouTubeFmtQuality = "17";
		WifiManager lWifiManager = (WifiManager) VideoPlayActivity.this.getSystemService(Context.WIFI_SERVICE);
		TelephonyManager lTelephonyManager = (TelephonyManager) VideoPlayActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
		if ((lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0)
				|| ((lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS || lTelephonyManager.getNetworkType() == 5 /* EVDO_0 */
						|| lTelephonyManager.getNetworkType() == 6 /**/
						|| lTelephonyManager.getNetworkType() == 8 /* HSDPA */
						|| lTelephonyManager.getNetworkType() == 9 /*
																	 * HSUPA -
																	 * 5.76
																	 * Mbit/s
																	 */
				|| lTelephonyManager.getNetworkType() == 10 /* HSPA */) && lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)) {
			lYouTubeFmtQuality = "18";
		}
		mVideoView.setYoutubeId(lYouTubeFmtQuality, url);
		mVideoView.requestFocus();
		mVideoView.start();
	}

	public String checkVideoPath(String path) {
		return path.replaceAll(" ", "%20");
	}

	@Override
	protected void onPause() {
		super.onPause();
		mVideoView.suspend();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mVideoView.resume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.homeObject = null;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// if (true) {
		calculateVideoViewSize();
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
			mVideoView.setFullScreen(true);
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
			// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
			// WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			mVideoView.setFullScreen(false);
		}
		mVideoView.setDimensions(width, height);
		mVideoView.getHolder().setFixedSize(width, height);
		bar.refreshDrawableState();
		// } else {
		// mVideoView.setDimensions(0, 0);
		// if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
		// menuFragment.YPlayer.setFullscreen(true);
		// } else if (newConfig.orientation ==
		// Configuration.ORIENTATION_PORTRAIT) {
		// menuFragment.YPlayer.setFullscreen(false);
		// }
		// }
	}

	private void calculateVideoViewSize() {
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		if (metrics.widthPixels < metrics.heightPixels) {
			height = (int) (metrics.widthPixels / 1.66);
			width = metrics.widthPixels;
		} else {
			width = metrics.widthPixels;
			height = metrics.heightPixels;
		}
		LinearLayout.LayoutParams layoutParams = (android.widget.LinearLayout.LayoutParams) relativeLayout.getLayoutParams();
		layoutParams.height = height;
		relativeLayout.setLayoutParams(layoutParams);
		relativeLayout.requestLayout();
	}

	@Override
	public void onToggleFullScreen(boolean isFullScreen) {
		setRequestedOrientation(isFullScreen ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	private String getHTMLData(String newsURL) {

		StringBuffer sb = new StringBuffer();
		sb.append("<html>");
		sb.append("<head>");
		// sb.append("<title>Anggota TNI ikut demo untuk beri rasa aman</title>");
		sb.append("<title>Funplus.vn</title>");
		sb.append("</head>");
		sb.append("<body>");
		// sb.append("<h1>Anggota TNI ikut demo untuk beri rasa aman</h1>");
		// sb.append("<h1>Comment facebook</h1>");
		// sb.append("<div style='color: #959595;'>Saucaca, 25-02-2015</div>");
		sb.append("<div class=\"fb-comments\" data-href=\"" + newsURL + "\" data-num-posts=\"5\" data-width=\"680\"></div>");
		sb.append("<div id=\"fb-root\"></div>");
		sb.append("<script>(function(d, s, id) {");
		sb.append("var js, fjs = d.getElementsByTagName(s)[0];");
		sb.append("if (d.getElementById(id)) {return;}");
		sb.append("js = d.createElement(s); js.id = id;");
		sb.append("js.src = \"//connect.facebook.net/en_US/all.js#xfbml=1&appId=1375226042786650\";");
		sb.append("fjs.parentNode.insertBefore(js, fjs);");
		sb.append("}(document, 'script', 'facebook-jssdk'));");
		sb.append("</script>");
		sb.append("</body>");
		sb.append("</html>");

		return sb.toString();
	}

	private LinearLayout.LayoutParams getLayoutParams() {
		return new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
	}

	private class FaceBookClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.i("REQUEST URL", url);
			return false;
		}
	}

	final class FBChromeClient extends WebChromeClient {

		@Override
		public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
			childWebView = new WebView(VideoPlayActivity.this);
			childWebView.getSettings().setJavaScriptEnabled(true);
			childWebView.getSettings().setSupportZoom(true);
			childWebView.getSettings().setBuiltInZoomControls(true);
			childWebView.setWebViewClient(new FaceBookClient());
			childWebView.setWebChromeClient(this);
			childWebView.setLayoutParams(VideoPlayActivity.this.getLayoutParams());

			parentLayout.addView(childWebView);

			childWebView.requestFocus();
			webViewFB.setVisibility(View.GONE);
			WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
			transport.setWebView(childWebView);
			resultMsg.sendToTarget();
			return true;
		}

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			VideoPlayActivity.this.setProgress(newProgress * 100);
		}

		@Override
		public void onCloseWindow(WebView window) {
			parentLayout.removeViewAt(parentLayout.getChildCount() - 1);
			childWebView = null;
			webViewFB.setVisibility(View.VISIBLE);
			webViewFB.requestFocus();
		}

	}
}